package view
{
	import controller.GameController;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import model.Product;

	public class Shelf extends Sprite
	{
		private var upperRightStartPosition:Object = new Object();
		private var shelfDistance:uint = Config.ShelfDistancePixX;
		private var boxDistancePixY = Config.BoxDistancePixY;
		private var productWidthInShelf = Config.ProductWidthInShelf;
		private var productHeightInShelf = Config.ProductHeightInShelf;
		private var productDistanceX = Config.ProductDistanceX;
		
		private var productWrappers:Array = new Array();
		
		public function Shelf(products:Array):void
		{
			this.upperRightStartPosition.x = Config.UpperRightShelfCornerX;
			this.upperRightStartPosition.y = Config.UpperRightShelfCornerY;
			this.fillShelf(products);
			
		}
		
		private function mixArray (array:Array):Array
		{
			return  array.sort (function () {return Math.floor(Math.random()*array.length-1);});
		}
		
		
		private function fillShelf(products:Array):void
		{
			products = mixArray(products);
			var x:uint = this.upperRightStartPosition.x;
			var y:uint = this.upperRightStartPosition.y;
			
			for (var i = 0; i <= products.length - 1; i++) {
				trace(i+1,x, y);
				this.productWrappers.push(new ProductWrapper(products[i], x, y));

				var productCount = i + 1;
				if (productCount % 6 == 0) { //jump down to beginning of next line
					x = this.upperRightStartPosition.x;
					y = + this.productHeightInShelf
						+ this.boxDistancePixY
						+ y;
				} else if (productCount % 2 == 0 && productCount % 6 != 0) { //jump right to next shelf
					x = x
						+ this.shelfDistance
						+ this.productWidthInShelf ;					
				} else {
					x = x 
						+ this.productWidthInShelf
						+ this.productDistanceX;
				}
				this.addChild(this.productWrappers[i]);	//add current wrapper sprite to shelf 
			}
		}
			
		public function letNextProductFly(gameController:GameController):void {
			// Laufband ermitteln
			var track:int = (Math.floor((Math.random()*3)));
			//track = 2;
			trace("ermitteltes Laufband: " + track);
			// Produkt ermitteln
			var productNum:int = (Math.floor((Math.random()*18)));
			var product:ProductWrapper = productWrappers[productNum];
			product.animateTo(product, Config.productTrack[track], gameController);
			
			/*
				 - randomly choose product wrapper - jup
				 - animate it by use of product wrapper animate() - jup
				 - listenes for catching or not catching - no
				 - let level check if product has to be catched or not, save it failure array if has to be - no
				 - if failure, tell the ProjectWrapper to put the Produkt back into its starting Position - no
			*/
		}
		
		public function addEventBtnListener(e:String, listener:Function) {
			this.addEventListener(e, listener);
		}
	}
}